package com.example.androidlearning2200;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

import com.example.androidlearning2200.service.MessageService;
import com.example.androidlearning2200.service.MusicService;

/**
 * Service使用详解
 * 1. Start方式启动Service
 * 2. Bind方式绑定Service
 * 3. 如果需要与Service建立通信，就采用绑定的方式，它会返回IBinder作为通信桥梁；如果不需要建立通信，只是单纯的其他Service，就采用启动的方式。
 */
public class ServiceActivity extends AppCompatActivity {

    private MusicService.MyBinder myBinder;
    private ServiceConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        findViewById(R.id.btnBindService).setOnClickListener(view -> bindMusicService());
        findViewById(R.id.btnPlayMusic).setOnClickListener(view -> playMusic());
        findViewById(R.id.btnUnbindService).setOnClickListener(view -> unbindMusicService());
        findViewById(R.id.btnStartService).setOnClickListener(view -> startMessageService());
        findViewById(R.id.btnStopService).setOnClickListener(view -> stopMessageService());
    }

    /**
     * 启动MessageService
     */
    private void startMessageService() {
        startService(new Intent(ServiceActivity.this, MessageService.class));
    }

    /**
     * 停止MessageService
     */
    private void stopMessageService() {
        stopService(new Intent(ServiceActivity.this, MessageService.class));
    }

    /**
     * 绑定 MusicService
     */
    private void bindMusicService() {
        Intent intent = new Intent(ServiceActivity.this, MusicService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                myBinder = (MusicService.MyBinder) iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    /**
     * 播放音乐
     */
    private void playMusic() {
        if (myBinder != null) {
            myBinder.play(R.raw.music1);
        } else {
            Toast.makeText(ServiceActivity.this, "请先绑定MusicService", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 解绑 MusicService
     */
    private void unbindMusicService() {
        if (connection != null) {
            unbindService(connection);
            connection = null;
            myBinder = null;
        }
    }

}